/**
 * Created by huangchao on 08/01/2018.
 */
import Form from '../form/form'
import drop from '../droplist/droplist'
import H from '../helper/helper'
import { userTypeVerDoAjax } from '../detail/detail';
import config from '../config';
import {logout, initSso, init} from '../top/top';

import {
  DROPDATA,
  DROPDATA_FILTER,
  DROPDATA_CHILDREN_MAP,
  DROPDATA_INDEX
} from './init'

$(function () {
  init()
  var $search = $('.w-search')

  $search.on('click', '.search-more', function() { //======展开折叠
      var $keywork = $('.w-keyworks'),
        $bottom = $('.form-bottom');
      if ($keywork.hasClass('action')) {
        $search.find('.search-form-box').stop(true).slideUp();
        $keywork.removeClass('action');
        $bottom.removeClass('action');
      } else {
        $search.find('.search-form-box').stop(true).slideDown();
        $keywork.addClass('action');
        $bottom.addClass('action');
      }
    })
    .on('click', '.clear-form', function() {  //====清空搜索条件
      $search.find('[control=select]').each(function() {
        var $me = $(this).removeClass('isSet'),
          $i = $me.children('i'),
          $input = $me.children('input');
        $i.html($i.attr('pla'));
        // $input.val(DROPDATA[$me.data('v')][0][0]);
        $input.val(0);
      }).filter('[isdropitem]').addClass('disabled').removeClass('isSet');

      // 拓展的input [work_year_min, salary_min, salary_max]
      $search.find('.form-box>input[type=hidden]').val('');

      // 职位性质
      $search.find('.work-mode span').eq(0).click();
      // 关键字类型
      /*$search.find('.search-val').val('')
       .siblings('.search-type').find('.search-list li').eq(0).click();*/
    })
    .on('click', '.work-mode span', function() { //=====单选框
      var $self = $(this),
        $cbox = $self.children('input'),
        $sibs;

      $cbox.prop('checked', true);
      if ($cbox.val() == 0) {
        $sibs = $self.addClass('active').siblings('span');
      } else if (!$self.hasClass('active')) {
        $sibs = $self.addClass('active').siblings('span').eq(0);
        if ($self.siblings('span.active').length == $self.siblings('span').length - 1) {
          $self.siblings('span').eq(0).click();
          return;
        }
      } else if ($self.siblings('span.active').length == 0) {
        $self.siblings('span').eq(0).click();
        return;
      } else {
        $sibs = $self;
      }
      $sibs.removeClass('active').children('input').prop('checked', false);
    });

  if (!$search.find('.work-mode span.active').length) {
    $search.find('.work-mode span').eq(0).click();
  }

  /**
   * 下拉框关联处理
   */

  function add_disable($me, item, unSetItem) {
    var $item = $me.siblings('[data-v=' + $me.attr('drop-item') + ']').attr('isDropItem', '');

    if ($item.length) {
      var $i = $item.data('dropItem', unSetItem ? '' : item)[(unSetItem ? 'add' : 'remove') + 'Class']('disabled').removeClass('isSet').find('i');
      $i.html($i.attr('pla')).siblings('input[type=hidden]').val('');
      // 递归将所有选项卡重置
      add_disable($item, '', true);
    }
  }

  /**
   * 下拉框关联处初始化
   */
  function disableInit($me) {
    // 获取 $me 的下级下拉框
    var i,
      $item = $me.siblings('[data-v=' + $me.attr('drop-item') + ']').attr('isDropItem', ''),
      itemv;
    var _propType = $me.data('v')
    i = 0
    while (true) {
      if (DROPDATA[_propType][i] && DROPDATA[_propType][i][0] == $me.find('input[type=hidden]').val()) {
        itemv = DROPDATA[$me.data('v')][i]
        break;
      }
      if (i++ > DROPDATA[_propType].length) {
        break;
      };
    }


    if ($item.length && itemv && itemv.length > 2) {
      $item.removeClass('disabled').data('dropItem', itemv[2]);
      // 递归将所有选项卡重置
      disableInit($item);
    }
  }

  var $control = $('[control=select][data-v=company_industry]');
  $control.length && disableInit($control);

  $search.on('click', '[control=select]', function(ev) { //======下拉选择
    var $self = $(this),
      name = $self.find('input[name]').attr('name'),
      $tpl,
      hasItem = $.inArray(name, ['company_industry', 'company_type']) >= 0;

    if ($self.hasClass('disabled')) {
      return;
    }

    $tpl = drop({
      $dom: $self,
      data: DROPDATA,
      filter: DROPDATA_CHILDREN_MAP[$self.data('dropItem')],
      skin: 'w-search-drop'
    }, function(val, item) {
      var unSetItem = item == undefined;
      if (hasItem) {
        add_disable($self, item, unSetItem)
      }

      if ($.inArray(name, ['work_year', 'salary']) >= 0) {
        var filter = DROPDATA_FILTER[name][val],
          sal = (filter ? filter : '-').split('-');
        $self.siblings('input[name=' + name + '_min]').val(sal[0]).siblings('input[name=' + name + '_max]').val(sal[1]);
      }
    });

    if ($self.hasClass('active')) {
      $tpl.hide();
    } else {
      $tpl.resize(12).move(1);
    }
    ev.stopPropagation();
  });

  /**
   * 表单提交操作
   */

  var search = new Form('#job-search-form'),
    tipsConfig = {
      tips: [3, '#FF9900'],
      time: 2400
    },
    $inkeys = $search.find('[name=funtype],[name=jobarea],[name=key_words]'),
    $keyInput = $inkeys.filter('.search-val');

  $search.on('click', '.search-btn, .J_submit', function(ev) {
    var hasN,
      placeholder = '请输入职位名或者关键字';

    setTimeout(function() {
      var keyPlaceholder = $keyInput.attr('placeholder')
      var keyVal = $.trim($keyInput.val())

      $inkeys.each(function() {
        var $me = $(this),
          v = $.trim($me.val());

        if (v != '' && v != $me.attr('placeholder')) {
          hasN = true;
          return false;
        }
      });

      if (hasN || (keyVal != placeholder && keyPlaceholder != placeholder)) {
        if (keyVal == '' && keyPlaceholder != placeholder) {
          $keyInput.val(keyPlaceholder);
        } else if (keyVal == placeholder) {
          $keyInput.val('');
        }
        search.submit();
      } else {
        layer.tips('请输入关键字，或者选择职位类型/工作地点哦！', $search.find('.search-bar .search-val'), tipsConfig);
      }
    }, 100);
    ev.preventDefault();
  });

  /**
   * 修复ie下在input中按回车使用默认submit提交的bug
   */
  $search.on('submit', function(ev) {
    $search.find('.search-btn, .J_submit').click();
    ev.preventDefault();
  });


  /*
   *
   * ================  筛选模块
   **/

  var $screen = $('.w-screen'), $doc = $(document);

    /**
     * 更多
     */
    $screen
  .find('.child-screen').each(function() {
    var $child = $(this).find('.child-all');
    $child.find('.active').prependTo($child);
  }).end()
    .find('.child-all').each(function() {
      var $this = $(this);
      if ($this.height() > 45) {
        $this.parent().after('<span class="more-show">更多</span>')
      }
    }).end()
    .on('mouseenter', '.more-show', function() {
      $(this).parents('.child-screen').addClass('active').siblings().removeClass('active');
    }).on('click', '.more-show', function() {
      $(this).parents('.child-screen').toggleClass('active');
    }).on('mouseleave', '.child-screen', function() {
      var $this = $(this);
      this.screen_more_delay = setTimeout(function() {
        $this.removeClass('active');
      }, 500);
    }).on('mouseenter', '.child-screen', function() {
      clearTimeout(this.screen_more_delay);
    });


// var joblist = require('../joblist/joblist');
  function getTimer(offset) {
    var time = new Date;
    time.setTime(time.valueOf() - _SERVER_TIME_OFFSET); // 服务器时间偏移
    time.setDate(time.getDate() + (offset || 0)); // 参数时间偏移
    return time.getFullYear() + '-' + H.pad(time.getMonth() + 1, 2) + '-' + H.pad(time.getDate(), 2);
  }


  /**
   * 条件筛选
   */
  function where_second() {
    var vals = $screen.find('.drops form').serializeArray(),
      arr_where_filter_second = '',
      i, len, name, value;

    for (i = 0, len = vals.length; i < len; i++) {
      name = vals[i]['name'];
      value = vals[i]['value'];
      if (name == 'job_update_time') {
        // 更新日期
        if (value && value != 0) {
          arr_where_filter_second += name + ' >-s||' + getTimer(-value) + '*';
        }
      } else if (name == 'salary') {
        // 月薪范围
        if (value && value != 0) {
          value = DROPDATA_FILTER[name][value].split('-');
          arr_where_filter_second += 'salary_min-s||' + value[0] + '*' + 'salary_max-s||' + value[1] + '*';
        }
      } else if (value && value != 0) {
        arr_where_filter_second += name + '-s||' + value + '*';
      }
    }
    arr_where_filter_second = arr_where_filter_second.slice(0, -1);

    // joblist.where('arr_where_filter_second', arr_where_filter_second);
  }


  $screen.on('click', '[control=select]', function(ev) {
    var name = $(this).find('input[name]').attr('name');

    var $self = $(this),
      $tpl = drop({
        $dom: $self,
        data: DROPDATA,
        skin: 'w-screen-drop'
      }, where_second);

    if ($self.hasClass('active')) {
      $tpl.hide();
    } else {
      $tpl.resize(12).move(1);
    }
    ev.stopPropagation();
  });

  /*
  * ======列表明细
  * */

  var li = '.w-tabmenu li', $tabmenu = $('.w-tabmenu');

  $doc.on('mouseenter', li, function() {
    $(this).addClass('hover');
  }).on('mouseleave', li, function() {
    $(this).removeClass('hover');
  })

  var tabtimer;
  $tabmenu.on('mouseover', '.w-tab-show, .tabright', function() {
    clearTimeout(tabtimer);
    $tabmenu.find('.tabright').removeClass('hide')
  }).on('mouseout', '.tabright', function() {
    tabtimer = setTimeout(function() {
      $tabmenu.find('.tabright').addClass('hide');
    }, 500)
  });

  var jlStyle = '.joblist-style span';
  $tabmenu.on('click', jlStyle, function() {
    var $self = $(this);
    $self.addClass('action').siblings().removeClass('action');
    $('.w-joblist .joblist .abstract')[$self.hasClass('wtm-whole') ? 'slideDown' : 'slideUp'](300)
  }).find(jlStyle).eq(0).click();

  /*
  *
  *==========全选
  * */

  var $jobbottom = $('.w-jobbottom'),
    $joblist = $('.w-joblist'),
    check = '.base .job input[type=checkbox]';


  function checks() {
    return $joblist.find('.job-child input.checked').closest('.job-child');
  }


  function checkAll() {
    var url = [];
    checks().each(function() {
      url.push($(this).data('id'));
    });

    $jobbottom.find('.J-shows')
      .attr('href', url.length ? '/job_search/job_show/' + url.join('-') : 'javascript:')
      .attr('target', url.length ? '_blank' : ''); // 解决ie9一下兼容问题
  }


  $jobbottom
    .on('change', '.selectAll', function() {
      console.log('selectAll')
      var ck = $(this).prop('checked');
      $joblist.find(check).prop('checked', ck)[(ck ? 'add' : 'remove') + 'Class']('checked');
      checkAll();
    })

    .on('click', '.J-shows', function() {
      var $shows = checks();
      !$shows.length && layer.message({
        right: '<h4>啊哦，不能显示</h4><span>您没有选中任何职位哦！</span>',
        icon: 2
      });
    });

  $joblist.on('click', check, function(ev) {
    var $self = $(this);
    setTimeout(function() {
      var $check = $joblist.find(check),
        ck = $self.prop('checked');

      $self[(ck ? 'add' : 'remove') + 'Class']('checked');
      $jobbottom.find('.selectAll').prop('checked', ck && $check.length == $check.filter('.checked').length);
      checkAll();
    });
    ev.stopPropagation();
  });

  /**
   *  超长文本截断
   */
// 多行
  $joblist.find('.job-child .abstract').each(function() {
    var $me = $(this);
    $me.html(H.substring($me.text(), 255));
  });


// 低版本单行兼容
  if (!$('body').css('maxWidth')) {
    $('.w-joblist .job-child').each(function() {
      var $self = $(this),
        $job = $self.find('.base .job a'),
        $hotel = $self.find('.base .hotel a');

      $job.html(H.substring($job.html(), 33)).css('width', '');
      $hotel.html(H.substring($hotel.html(), 24));
    });
  }


  /**
   * 关键字标红
   */
// var keyWord = _ARR_KEY_WORDS.length ? RegExp('(' + _ARR_KEY_WORDS.join('|') + ')', 'ig') : null;
  function keyOut($list) {
    if (keyWord) {
      $list.find('.job a, .hotel a, .attr .brief').each(function() {
        var $me = $(this);
        $me.html($me.html().replace(keyWord, '<b>$1</b>'));
      });
    }
  }
// keyOut($joblist);


  /**
   * 电话直聘
   */
  $joblist.on('click', '.base .job .call', function() {
    userTypeVerDoAjax(config.jsonpBase + '/pop/show_tel', {
      job_id: $(this).closest('.job-child').data('id')
    }, function(data) {
      layer.message('<p>欢迎来电应聘/咨询：<strong>' + data.message.contact_telephone + '</strong><br>咨询时间：' + (data.message.contact_time == '00:00-00:00' ? '24 x 7' : data.message.contact_time) + '</p>', 2, {
        title: '电话直聘'
      });
    });
  });

})